<?php
require_once 'Zend/Controller/Action.php';
require_once 'Zend/Auth.php';
require_once 'Zend/Auth/Adapter/DbTable.php';

class Acceso_AuthController extends Zend_Controller_Action {

	public function init() {
		$registry = Zend_Registry :: getInstance();
		$this->db = $registry->db;
		$this->smarty = $registry->smarty;
		$this->smarty->assign('baseUrl', $this->getRequest()->getBaseUrl());
		$this->smarty->assign('subtitulo', 'Login');
	}

	function indexAction() {
		$this->_redirect('/');
	}

	function loginAction() {

		if ($this->getRequest()->isPost()) {
			try {
				$userName = $this->getRequest()->getParam('usuario');
				$password = $this->getRequest()->getParam('password');
				$authAdapter = new Zend_Auth_Adapter_DbTable($this->db);
				$authAdapter->setTableName('USUARIO');
				$authAdapter->setIdentityColumn('USUARIO_MAIL');
				$authAdapter->setCredentialColumn('USUARIO_PASSWORD');
				$authAdapter->setIdentity($userName);
				$authAdapter->setCredential($password);
				$auth = Zend_Auth :: getInstance();
				$result = $auth->authenticate($authAdapter);

				if ($result->isValid()) {
					$data = $authAdapter->getResultRowObject(null, 'password');
					$auth->getStorage()->write($data);
					$this->_redirect('/');
				} else {
					$this->smarty->assign('mensajeError', 'Error en tu usuario y/o contrase&ntilde;a.');
				}

			} catch (Exception $e) {
				$this->smarty->assign('mensajeError', 'Error!' . $e->getMessage());
			}
		}
		$this->smarty->displayInMasterPage('acceso_auth_login.tpl', 'MasterPage.tpl');
	}

	function logoutAction() {
		Zend_Auth :: getInstance()->clearIdentity();
		Zend_Session :: namespaceUnset('Gea_Zend_Acl_Factory');
		$this->_redirect('/');
	}
}
?>